package com.learn.springboot.service.order;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.learn.springboot.dao.dto.OrderRuleExcelDto;
import com.learn.springboot.dao.mapper.LiveTimeInfoMapper;
import com.learn.springboot.dao.mode.LiveTimeInfo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.spring.SpringUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author suzheng
 * @date 2020-06-17
 **/
@Slf4j
public class ImportOrderExcelRuleSheetListener extends AnalysisEventListener<OrderRuleExcelDto> {

    @Getter
    private List<OrderRuleExcelDto> orderRules = new ArrayList<>(12);

    @Override
    public void invoke(OrderRuleExcelDto orderRuleExcelDto, AnalysisContext analysisContext) {
        String[] timeArr = orderRuleExcelDto.getLiveTime().replace("：", ":").split("-");
        String startTimeStr = timeArr[0];
        String endTimeStr = timeArr[1];
        if (startTimeStr.endsWith(":")) {
            startTimeStr = startTimeStr + "00";
        }
        if (startTimeStr.length() == 5) {
            startTimeStr = startTimeStr + ":00";
        }

        if (endTimeStr.endsWith(":")) {
            endTimeStr = endTimeStr + "00";
        }
        if (endTimeStr.length() == 5) {
            endTimeStr = endTimeStr + ":00";
        }
        String dateStr = DateUtil.format(orderRuleExcelDto.getTimeDt(), DatePattern.NORM_DATE_PATTERN);
        orderRuleExcelDto.setTimeDtStr(dateStr);
        orderRuleExcelDto.setStartLiveTime(DateUtil.parseDateTime(StrUtil.format("{} {}", dateStr, startTimeStr)));
        orderRuleExcelDto.setEndLiveTime(DateUtil.parseDateTime(StrUtil.format("{} {}", dateStr, endTimeStr)));
        orderRules.add(orderRuleExcelDto);
        log.debug("{}", orderRuleExcelDto);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        MD5 md5 = MD5.create();

        List<LiveTimeInfo> liveTimeInfoList = orderRules.stream().map(orderRuleExcelDto -> {
            LiveTimeInfo liveTimeInfo = BeanUtil.toBean(orderRuleExcelDto, LiveTimeInfo.class);
            String rawStr = StrUtil.format("{}{}{}", DateUtil.format(liveTimeInfo.getTimeDt(), DatePattern.PURE_DATE_PATTERN),
                    liveTimeInfo.getAccount(),
                    liveTimeInfo.getTimeName());
            liveTimeInfo.setMd5(md5.digestHex(rawStr));
            return liveTimeInfo;
        }).collect(Collectors.toList());

        SpringUtil.getBean(LiveTimeInfoMapper.class).batchInsert(liveTimeInfoList);
        log.info("所有数据解析完毕");
    }
}
